#include <iostream>
#include <dlib/image_io.h>
#include "ConfigParser.h"
#include "FaceRecognizer.h"

int main() {
    // 加载配置文件
    ConfigParser config;
    if (!config.load("/home/ubuntu/practice/dlib/myapp4/config.txt")) {
        std::cerr << "配置文件加载失败" << std::endl;
        return -1;
    }
    
    // 打印配置文件内容（调试用）
    if (config.get("debug") == "true") {
        config.printAll();
    }
    
    // 创建人脸识别器
    try {
        FaceRecognizer face_recognizer(config);
        
        // 打印人脸库信息
        face_recognizer.printFaceLibInfo();
        
        // 测试1：使用配置文件中指定的已知人脸图片
        std::string known_image_path = config.get("jpg_path");
        if (known_image_path.empty()) {
            std::cerr << "配置文件中未指定已知人脸图片路径 (jpg_path)" << std::endl;
            return -1;
        }
        
        std::cout << "\n[测试1] 使用已知人脸图片进行测试: " << known_image_path << std::endl;
        dlib::matrix<dlib::rgb_pixel> known_img;
        
        try {
            dlib::load_image(known_img, known_image_path);
        } catch (dlib::image_load_error& e) {
            std::cerr << "图片加载失败: " << e.what() << std::endl;
            return -1;
        }
        
        // 检测人脸
        auto faces = face_recognizer.detectFaces(known_img);
        if (faces.empty()) {
            std::cout << "未检测到人脸" << std::endl;
        } else {
            // 对齐人脸
            auto face_chip = face_recognizer.alignFace(known_img, faces[0]);
            // 识别人脸
            std::string result = face_recognizer.recognizeFace(face_chip);
            std::cout << "匹配结果: " << result << std::endl;
        }
        
        // 测试2：使用配置文件中指定的陌生人照片
        std::string stranger_path = config.get("stranger_path");
        if (stranger_path.empty()) {
            std::cerr << "配置文件中未指定陌生人图片路径 (stranger_path)" << std::endl;
            return -1;
        }
        
        std::cout << "\n[测试2] 使用陌生人照片进行测试: " << stranger_path << std::endl;
        dlib::matrix<dlib::rgb_pixel> stranger_img;
        
        try {
            dlib::load_image(stranger_img, stranger_path);
        } catch (dlib::image_load_error& e) {
            std::cerr << "陌生人图片加载失败: " << e.what() << std::endl;
            return -1;
        }
        
        // 检测人脸
        faces = face_recognizer.detectFaces(stranger_img);
        if (faces.empty()) {
            std::cout << "未检测到人脸" << std::endl;
        } else {
            // 对齐人脸
            auto face_chip = face_recognizer.alignFace(stranger_img, faces[0]);
            // 识别人脸
            std::string result = face_recognizer.recognizeFace(face_chip);
            std::cout << "匹配结果: " << result << std::endl;
        }
        
    } catch (const std::exception& e) {
        std::cerr << "错误: " << e.what() << std::endl;
        return -1;
    }
    
    return 0;
}